// components/capture/capture.js
Component({
  options: {
    styleIsolation: 'apply-shared'
  },

  /**
   * 组件的属性列表
   */
  properties: {
    path: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    localPath: '', // 本地图片路径
    cloudPath: '', // 云端图片路径
    uploading: false // 上传中
  },

  observers: {
    'path': function (value) {
      if (value && value.startsWith('cloud://')) {
        this.setData({ cloudPath: value })
      } else if (value) {
        this.uploadImage(value)
      } else {
        this.setData({ cloudPath: '' })
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 选择图片
     */
    bindChooseImage () {
      const _this = this;
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        success: function success(res) {
          const localPath = res.tempFilePaths[0]
          if (localPath) {
            _this.setData({ localPath })
            wx.navigateTo({
              url: `/pages/capture/capture?path=${localPath}`,
            })
          }
        },
        fail: function fail(_fail) {
          
        }
      })
    },

    /**
     * 上传图片
     * @param {String} filePath 文件路径
     */
    uploadImage(filePath) {
      const _this = this
      const date = new Date()
      const sn = date.getTime().toString() + Math.floor(Math.random() * 10000).toString()
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      month = month >= 10 ? month : '0' + month
      const cloudPath = `image/${year}${month}/${sn}${filePath.match(/\.[^.]+?$/)[0]}`
      this.setData({ uploading: true })
      wx.cloud.uploadFile({
        filePath,
        cloudPath,
        success: res => {
          // 删除原来的云端图片
          const lastCloudPath = _this.data.cloudPath
          if (lastCloudPath) {
            _this.deleteImage(lastCloudPath)
          }
          // 向父组件传递值
          _this.triggerEvent('change', { value: res.fileID })
        },
        fail: err => {
          wx.showToast({
            title: '上传失败'
          })
        },
        complete: () => {
          this.setData({ uploading: false })
        }
      })
    },
    
    /**
    * 删除云端图片
    * @param {String} url 远程图片路径
    */
   deleteImage (url) {
    wx.cloud.deleteFile({
      fileList: [url]
    })
   },
  }
})
